package controller;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import model.Mesa;

public class AddMesaBean {
    private int id;
    private int chairs;
    private String location;
    private int active;
    private int busy;
	
	private String errors;
	
	public String getErrors(){return errors;}
    public int getId() {return id;}
    public String getLocation(){return location;}
    public int getChairs() {return chairs;}
    public int getActive () {return active;}
    public int getBusy() {return busy;}

    public void setErrors( String s ) {errors = s;}
    public void setId(int id) {this.id = id;}
    public void setChairs(int chairs) {this.chairs = chairs;}
    public void setLocation(String location){this.location = location;}
    public void setActive(int s) {active = s; }
    public void setBusy(int s) {busy = s;}
	
    public String modify(){
		try {
			validateField(""+this.id);
			validateField(""+this.chairs);
			validateField(this.location);
			validateField(""+this.busy);
		} catch (Exception e) {
			errors = "Hubo un error en uno de los campos";
			return null;
		}
		
		Mesa m = new Mesa();
		m.setActive(1);
		m.setChairs(chairs);
		m.setBusy(busy);
		m.setLocation(location);
		
		if(m.modify(id,chairs,location,busy)) {
			FacesContext context = FacesContext.getCurrentInstance();
			HttpSession session = (HttpSession) context.getExternalContext().getSession(true);				
			session.setAttribute("message", "Mesa actualizada exitosamente");
			return "success";
		}
			
		else 
			return null;
	}

	public String delete(){
		try {
			validateField(""+this.id);
			validateField(""+this.chairs);
			validateField(this.location);
			validateField(""+this.busy);
		} catch (Exception e) {
			errors = "Hubo un error en uno de los campos";
			return null;
		}
		
		Mesa m = new Mesa();
		m.setActive(1);
		m.setChairs(chairs);
		m.setBusy(busy);
		m.setLocation(location);
		
		if(m.delete(id))
			return "success";
		else
			return null;
	}
    
	public String add(){
		try {
			validateField(""+this.id);
			validateField(""+this.chairs);
			validateField(this.location);
			validateField(""+this.busy);
		} catch (Exception e) {
			errors = "Hubo un error en uno de los campos";
			return null;
		}
		
		Mesa m = new Mesa();
		m.setActive(1);
		m.setChairs(chairs);
		m.setBusy(busy);
		m.setLocation(location);
		
		if(m.register(chairs,location,busy)){
			FacesContext context = FacesContext.getCurrentInstance();
			HttpSession session = (HttpSession) context.getExternalContext().getSession(true);				
			session.setAttribute("message", "Mesa agregada exitosamente");
			return "success";
		}
			
		else
			return null;
	}
	
	private void validateField(String value) throws Exception {
		if ( value == null || value.length() == 0 )
			throw new Exception();	
	}
}
